<script src="../../common/js/quill-config.js"></script>
<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <!--其他都设置值,只有一个不设置值就自动适应了-->
      <el-table-column prop="name" label="课程名称" >
      </el-table-column>
      <el-table-column prop="chapterCount" label="章节数" >
      </el-table-column>
      <!--<el-table-column prop="courseType.name" label="类型">-->
      <!--</el-table-column>-->
      <el-table-column prop="gradeName" label="等级" >
      </el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormatter">
      </el-table-column>
      <el-table-column prop="forUser" label="适用人群" width="220">
      </el-table-column>
      <!--<el-table-column prop="tenantName" label="所属机构">-->
      <!--</el-table-column>-->
      <el-table-column prop="teacherNames" label="讲师" width="140">
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" v-if="scope.row.status==0" @click="onOneSale(scope.$index, scope.row)">上架</el-button>
          <el-button size="small" v-else @click="offOneSale(scope.$index, scope.row)">下架</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--批量删除-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-button type="danger" @click="batchOnSale" :disabled="this.sels.length===0">批量上架</el-button>
      <el-button type="danger" @click="batchOffSale" :disabled="this.sels.length===0">批量下架</el-button>
      <el-pagination layout="sizes,prev, pager, next"
                     @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :page-sizes="[5, 10, 20, 50]" :page-size="pageSize" :current-page.sync="currentPage"
                     :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>
    <!--新增和修改对话框
    :title="title" 动态绑定标题，点击[新增/编辑]title=新增/编辑
    :visible.sync="saveFormVisible" 对话框的显示状态，true/false 显示/隐藏
    :close-on-click-modal="false" 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框

    el-form - 表单
    :model="saveForm" - 绑定表单对象
    label-width="80px" - 标签宽度
    :rules="saveFormRules" - 验证规则
    ref="saveForm" - 为当前模态框取名
    prop="name" - 如果当前字段要验证，就必须写，出现*
    auto-complete="off" - 不自动提示
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="课程名称" prop="name" >
          <el-input v-model="saveForm.name" placeholder="课程名称" auto-complete="off" style="width: 300px" />
        </el-form-item>
        <el-form-item label="适用人群" prop="forUser">
          <el-input v-model="saveForm.forUser" placeholder="适用人群" auto-complete="off" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseTypeId" >
          <!--el-cascader - 级联
             :options="deptTree" - 级联框中需要的数据【集合】-->
          <el-cascader v-model="saveForm.courseTypeId"
                       :options="deptTree"
                       :props="{
                          checkStrictly: true,
                          label: 'name', // 级联框显示那个属性的值
                          value: 'id'    // 回显时需要,回传值的时候也需要
                        }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="添加讲师" prop="teacherNames">
          <el-select v-model="saveForm.teacherNames" multiple placeholder="可选多个讲师" style="width: 300px">
            <el-option
                v-for="item in teachers"
                :key="item.id"
                :label="item.name"
                :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程周期" >
          <el-date-picker  style="width: 200px"
                           v-model="saveForm.startTime"
                           type="date"
                           value-format="yyyy-MM-dd"
                           size="small"
                           placeholder="课程开始日期">
          </el-date-picker> -
          <el-date-picker   style="width: 200px"
                            v-model="saveForm.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            size="small"
                            placeholder="课程结束日期">
          </el-date-picker>
        </el-form-item >

        <el-form-item label="购买可看" >
          <el-input placeholder="可看天数"  type="number" v-model="saveForm.validDays" auto-complete="off" style="width: 165px"/>&nbsp;天
        </el-form-item>

        <el-form-item label="课程等级" style="width: 700px">
          <el-radio-group v-model="saveForm.grade">
            <el-radio v-for="grade in grades" :label="grade" :value="grade">{{grade.name}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="logo" style="width: 400px" >
          <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://wyc-edu-demo.oss-cn-chengdu.aliyuncs.com"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="收费规则" size="width:100%">
          <el-radio-group v-model="saveForm.chargeId">
            <el-radio v-for="charge in charges" :label="charge.id" :value="charge.id">{{charge.name}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="课程价格" prop="price">
          <el-input :disabled="priceDisabled" type="number" v-model="saveForm.price" auto-complete="off" style="width: 185px"/>
        </el-form-item>
        <el-form-item label="课程原价">
          <el-input :disabled="priceDisabled" type="number" v-model="saveForm.priceOld" auto-complete="off" style="width: 185px"/>
        </el-form-item>

        <el-form-item label="咨询QQ" prop="qq">
          <el-input v-model="saveForm.qq" auto-complete="off" style="width: 150px"></el-input>
        </el-form-item>


        <el-form-item label="课程简介" prop="description">
          <el-input style="width: 450px"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="saveForm.description">
          </el-input>
        </el-form-item>

        <el-form-item label="课程详情" prop="intro">
          <div class="edit_container">
            <quill-editor
                v-model="saveForm.intro"
                ref="myQuillEditor"
                class="editer"
                :options="editorOption"
                @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css"
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
  [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{font: []}], // 字体种类-----[{ font: [] }]
  [{align: []}], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];
export default {
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  components: {//使用编辑器
    quillEditor
  },
  data() {
    return {
      priceDisabled:true,
      //保存的图片
      fileList:[],
      uploadData: {  //提交到OSS的参数
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: ''
      },
      teachers:[],
      editorOption: {},//富文本编辑框配置
      grades:[
        {id:1,name:"青铜"},{id:2,name:"白银"},{id:3,name:"黄金"},{id:4,name:"白金"},{id:5,name:"钻石"}
      ],
      charges:[
        {"id":1 , "name":"免费"},
        {"id":2 , "name":"收费"}
      ],
      //1.数据列表相关的模型数据
      pageInfo:{
        list:[],
        total:0
      },
      listLoading: false, //盲等框，默认不显示
      //分页列表
      total: 0,  //总条数
      pageSize: 5,  //条数
      currentPage:1, //当前页
      //3.高级查询
      keyword:"",
      //列表选中列
      sels: [],

      //5.对话框
      title:'',//对话框标题
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,//盲等框-在提交按钮上
      saveFormRules: {//验证规则
        name: [ //trigger: 'blur' 失去焦点时触发
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        courseTypeId: [
          { required: true, message: '请选择课程类型' }
        ],
        grade: [
          { required: true, message: '请选择收费等级' }
        ],
        chargeId: [
          { required: true, message: '请选择收费规则' }
        ],
        teacherNames: [
          { required: true, message: '请选择讲师' }
        ],
      },
      //编辑界面数据,建议数字用null，字符串用''
      saveForm: {
        id:null,
        startTime:'',
        endTime:'',
        validDays:'',
        name:'',
        forUser:'',
        grade:null,
        gradeId:null,
        gradeName:null,
        teacherNames:'',
        courseTypeId:'',
        description:'',
        intro:'',
        chargeId:'',
        price:'',
        priceOld:'',
        qq:'',
        pic:'',
        zipResources:''
      },
      //课程类型树
      deptTree:[]
    }
  },
  methods: {
    batchOnSale(){
      // 获取当前被选中数据的id数组
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/course/onsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getCourses();
        });
      }).catch(() => {

      });
    },
    batchOffSale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/course/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getCourses();
        });
      }).catch(() => {

      });
    },
    onOneSale(index,row){},
    offOneSale(index,row){},
    getUUID() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";
      var uuid = s.join("");
      return uuid;
    },
    async beforeUpload(){
      await this.$http.get("/oss/sign").then(res=>{
        //设置相关的参数
        var resultObj = res.data.data;
        this.uploadData.policy = resultObj.policy;
        this.uploadData.signature = resultObj.signature;
        this.uploadData.ossaccessKeyId = resultObj.accessid;
        //上传的文件名，使用UUID处理一下
        this.uploadData.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
        this.uploadData.dir = resultObj.dir;
        this.uploadData.host = resultObj.host;
      });
    },
    //文件上传成功回调
    handleSuccess(res, file, fileList){
      console.log("res",res)
      console.log("file",file)
      console.log("fileList",fileList)
      //上传的完整的文件地址
      var urlPath = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}",file.name) ;
      this.saveForm.pic = urlPath;
      this.$message({message: '上传成功，图片地址：'+this.saveForm.pic, type: 'success' });
    },
    //删除
    handleRemove(file, fileList) {
      console.log("shanchu"+this.saveForm.pic)
      this.$http.post('/oss',this.saveForm.pic)
          .then(res=>{
            var data = res.data;
            if(data.success){
              console.log("成功", data)
              console.log(this.saveForm.pic)
            }
          })
          .catch(res=> {
            console.log("失败", res)
            console.log(this.saveForm.pic)
          })
    },
    //下载
    handlePreview(file) {},
    onEditorReady(editor) {
      //当富文本编辑框初始化好执行
    },
    statusFormatter: function (row, column) {
      return row.status == 1 ? '已上线' : '未上线';
    },
    //获取课程列表
    getCourses() {
      let para = {
        pageSize: this.pageSize,  //条数
        currentPage:this.currentPage, //当前页
        keyword:this.keyword //高级查询关键字
      };
      //显示盲等框
      this.listLoading = true;
      //NProgress.start();
      //调用方法，在请求列表之前是mock，现在要请求后端 分页接口
      this.$http.post("/course",para).then(res=>{
        //1.关闭盲等框
        this.listLoading=false;
        //2.给列表数组赋值
        var data = res.data
        if(data.success){
          this.pageInfo = data.data
        }
      }).catch(res=>{
        //Message消息提示
        this.$message.error('网络繁忙，请稍后重试！');
      });
    },
    //2.分页点击事件
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCourses();
    },
    //3.当前页显示的条数
    handleSizeChange(pageSize){
      this.pageSize = pageSize;
      this.getCourses();
    },
    //4,高级查询点击事件
    keywordQuery() {
      this.currentPage = 1;
      this.getCourses();
    },
    //5.删除单个数据
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//1.发送请求显示盲等框
        //2.删除请求复合Restful风格
        this.$http.delete("/course/"+row.id).then(res=>{
          //关闭盲等框
          this.listLoading = false;
          if(res.data.success){//请求成功
            //提示成功
            this.$message.success("操作成功");
            //3.1针对当前页处理,获取到最后一页
            let tatalPage = Math.ceil(this.total/this.pageSize);
            //3.2 判断：1.最后一页；2.最后一条数据；3.并且不是第一页
            if (
                this.currentPage==tatalPage
                && (this.total-1)%this.pageSize==0
                && this.currentPage!=1
            ){
              //3.3 设置当前页为上一页
              this.currentPage=this.currentPage-1;
            }
            //4.重新查询列表
            this.getCourses();
          }else {//后端异常信息
            this.$message.error("网络繁忙，请稍后重试【后端异常错误500】");
          }
        }).catch(res=>{//请求失败
          this.$message.error("网络繁忙，请稍后重试【前端请求错误400,404】");
        })
      }).catch(() => {//出现异常不做任何操作
      });
    },
    //5.选中改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },
    //7.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);//[1,2,3]
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //打开盲等框
        this.listLoading = true;
        //ids是数组，要改造，注意
        this.$http.patch("/course",ids).then(res=>{
          //关闭盲等框
          this.listLoading = false;
          if(res.data.success){//请求成功
            //提示成功
            this.$message.success("操作成功");
            this.currentPage=1;
            //4.重新查询列表
            this.getCourses();
          }else {//后端异常信息
            this.$message.error("网络繁忙，请稍后重试【后端异常错误500】");
          }
        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试【前端请求错误400,404】");
        })
      }).catch(() => {

      });
    },
    //8.显示新增对话框
    handleAdd: function () {
      //显示对话框
      this.saveFormVisible = true;
      //标题
      this.title="新增";
      //根据属性名称赋值
      this.saveForm = {};
      //获取所有老师
      this.getTeachers();
      //查询课程类型树，新增-1，课程id没有-1
      this.getDeptTree(-1);
    },
    // 9.显示编辑对话框
    handleEdit: function (index, row) {
      //显示对话框
      this.saveFormVisible = true;
      //标题
      this.title="编辑";
      //this.saveForm = row;
      //把row赋给一个空对象，那么修改回显的数据，就不会改变row,分开的两个数据（双向绑定导致的问题）
      //属性名称赋值
      this.saveForm = Object.assign({}, row);
      //获取所有老师
      this.getTeachers();
      //查询类型树，编辑要传入自己的id，排除自己
      this.getDeptTree(row.id);
    },
    // 10.编辑或者新增执行的方法
    saveSubmit: function () {
      //表单验证，验证规则不通过无法提交，验证所有名称saveForm的对话框
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            //获取课程类型数组：情况：[]  [1,2]
            let arr=para.courseTypeId;
            // 判断为空时
            if(arr && arr.length==0){//数组中没有数据
              para.courseTypeId=null;//清理后是[]，要改为null
            }else if(arr && arr.length>0){
              para.courseTypeId=arr[arr.length-1];
            }

            //处理老师名称
            let names=para.teacherNames;
            // 判断为空时
            if(names && names.length==0){//数组中没有数据
              para.teacherNames=null;//清理后是[]，要改为null
            }else if(names && names.length>0){
                para.teacherNames+="";
            }

            //处理等级名称和id
            para.gradeId=para.grade.id;
            para.gradeName=para.grade.name;

            //处理时间格式
            para.startTime+=" 00:00:00";
            para.endTime+=" 23:59:59";


            this.$http.put("/course",para).then(res=>{
              //关闭盲等框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible=false;
              if(res.data.success){//请求成功
                //2.2提示保存成功
                this.$message.success(res.data.message);
                //2.3 新增返回最后一页，新增没有id
                if (para.id==null){
                  //新增是在原来的总条数上增加了一条，最后一页是满的，需要跳转到新的最后一页，
                  //总页数=线上取整(总条数/当前页条数)
                  this.total=this.total+1;//新增后的总条数
                  //当前页码重新赋值
                  this.currentPage=Math.ceil(this.total/this.pageSize);
                }
                //4.重新查询列表
                this.getCourses();
              }else {//后端异常信息
                this.$message.error("网络繁忙，请稍后重试【后端异常错误500】");
              }
            }).catch(res=>{
              this.$message.error("网络繁忙，请稍后重试【前端请求错误400,404】");
            })
          });
        }
      });
    },
    //11.查询所有Employee数据
    getTeachers(){
      this.$http.get("/teacher").then(res=>{
        //管理员赋值，后端直接返回的Employee集合json,直接取值data赋值
        this.teachers=res.data.data;
      }).catch(res=>{
        this.$message.error("网络错误【400/404】");
      })
    },
    //12.查询课程树
    getDeptTree(id){//不能查到自己，不能自己是自己的父类
      this.$http.get("/courseType/tree").then(res=>{
        this.deptTree=res.data.data;
      }).catch(res => {
        this.$message.error("网络错误【400/404】");
      })
    }
  },
  mounted() {
    this.getCourses();
  }
}

</script>

<style scoped>

</style>